package com.example.fragment;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fragment.tool.ActivityCollector;
import com.example.fragment.tool.CountNumbers;
import com.example.fragment.tool.DataBaseTool;
import com.example.fragment.tool.LogbuttonLayout;
import com.example.fragment.tool.MyApp;
import com.example.fragment.tool.ShowDownloadDialog;
import com.example.fragment.tool.ToastUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;
import lecho.lib.hellocharts.view.LineChartView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView testBn, resultBn, settingBn, right1Bn, right2Bn;
    private LogbuttonLayout signBn;
    private ImageView mIvOpen, mIvPrint, mIvUsb, mIvConnect, mIvNetwork;

    private boolean login = false;  //判断是否登录，默认为false

    private SingelShowFragment singelShowFragment;
    private ResultFragment resultFragment;
    private SettingFragment settingFragment;
    private MutilShowFragment mutilShowFragment;
    private GrameSettingFragment grameSettingFragment;
    private PeopleSettingFragment peopleSettingFragment;
    private SystemSettingFragment systemSettingFragment;
    private StartSetFragment startSetFragment;
    private static final String TABLE_NAME3 = "Person";
    ImageView testButton,  stopBn, changeBn,mIvinshow;
    private TextView mTv1;
    LinearLayout ll;
    private LineChartView LineChart,LineChart2,LineChart3,LineChart4,LineChart5,LineChart6,LineChart7,LineChart8,LineChart9,LineChart10, LineChart11,LineChart12,LineChart13,LineChart14,LineChart15,LineChart16;
    private SharedPreferences mSharedPreferences;//打开通道
    private TextView mTvn1, mTvn2,mTvn3, mTvn4, mTvn5,mTvn6, mTvn7, mTvn8,mTvn9, mTvn10, mTvn11,mTvn12,mTvn13, mTvn14,mTvn15,mTvn16;
    private android.content.SharedPreferences.Editor mEditor;
    private final String mFileName = "test.txt";//文件名
    private  int[] score,scorea,scorez,scorew,scores,scorex,scoree,scored,scorec,scorer,scoref,scorev,scoret,scoreg,scoreb,scorey;;//图表的数据点
    private  float gb;
    private LogbuttonLayout signupBn;
    private TextView mTvTemp1,mTvTimeL,mTvData;
    private int chengong;
    private CountNumbers countNumbers ;
    private String uername,usernumber;
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    //串口可能用到的
    private boolean isOpen=false;
    public int baudRate;
    public byte stopBit;
    public byte dataBit;
    public byte parity;
    public byte flowControl;
    private long Starttime;
    private long Endtime;
    private boolean isTest=false;
    private static boolean check123;
    private int countch340=0;
    private Handler mHandler;
    private String hang = "";
    private int hangsize=0;
    private Timer timer=new Timer("刷新");
    private boolean isFirst=true;
    private boolean isFirstprogress=true;
    private int timelong1=0;
    private byte bt;
    private boolean iscountinue=true;
    private ShowDownloadDialog waitdialog;
    private Thread thread =new Thread();
    private boolean status;
    private boolean is80=false;
    private boolean is40=false;
    private boolean is5min=false;
    private float anow;
    private int a40 = 0;
    private int a80 = 0;
    private static final String TABLE_NAME2 = "Test";

    private Handler handler2=new Handler(){
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1:
                    if(iscountinue){
                        handler2.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message message=new Message();
                                message.what=4;
                                handler2.sendMessage(message);
                                is5min=true;
                            }
                        },5000);
                    }

                    break;
                case 2:
                    final Timer timer=new Timer();
                    if(!is80){

                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                if(a80==6) {
                                    timer.cancel();
                                    a80=0;
                                }else {
                                    if(!is80) {
                                        byte[] d12 = new byte[]{0x36, (byte) 0xf1, 0x08, bt, 0x00, 0x00, (byte) 0xff};
                                        byte[] d11 = new byte[]{0x36, (byte) 0xf1, 0x08, bt, 0x00, 0x00, translate(d12), (byte) 0xff};
                                        Ch340write(d11);
                                        a80++;
                                    }
                                }

                            }
                        }, 0, 100);

                    }
                    break;
                case 3:
                    final Timer timer1=new Timer();
                    if(!is40){
                        timer1.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                if(a40==6) {
                                    timer1.cancel();
                                    a40=0;
                                }else {
                                    if (!is40){
                                        byte[] start= new byte[]{0x36, (byte) 0xf1, 0x04, 0x00, 0x00, 0x00, (byte) 0xc3,(byte) 0xff};
                                        Ch340write(start);
                                        a40++; }}
                            }
                        }, 0, 100);

                    }
                    break;
                case 4:
//                    dodata();
//                    alllineset();
                    Message message=new Message();
                    message.what=1;
                    handler2.sendMessage(message);
                    break;
                case 5:
                    int a1= (int) (anow*100);
                    waitdialog.setProgress1(a1);
                    break;
                default:
                    break;
            }
        };
    };


    private Handler  handler = new Handler() {
        public void handleMessage(Message msg) {

            String yourmessge=(String) msg.obj;
            Log.e("命令",yourmessge);
            List<String> list= Arrays.asList(yourmessge.split(" "));//将一长字符串。转换为数组++++++++++++++++++++++
            byte[] check=toByteArray(yourmessge);
            boolean isrecevive=false;
            boolean isstart1=false;
            if((check[6]==jocheck(check))&&(check[0]==0x36)&&(check[7]==(byte) 0xff)){
                if(check[1]!=(byte) 0xf1){
                    isrecevive=true;

                    int a1=check[2]*256+btou(check[3]);
                    if(check[1]== (byte) 0x0f){
                        hang+=a1+"\n";
                        hangsize+=1;
                        if(hangsize==16){
                            if(is5min){
                                save(hang);
                                is5min=false;
                                Log.e("消息receive",hang);
                            }
                        }
                        hangsize=0;
                        hang="";
                    }else {
                        hang+=a1+",";
                        hangsize+=1;
                    }

                } else {
                    switch (check[2]){

                        case (byte)0x70:
                            int a6=check[4]*256+btou(check[5]);
                            float a2=(float)a6;
                            float a3=a2/100;
                            anow=a2;
                            String time=getsystemtime1();
                            mTvTemp1.setText("温度："+a3+"℃");
                            if(isTest){
                                Endtime=getsystemtime();
                                String timelong=getTimeExpend(Starttime,Endtime);
                                String timelong2=getTimeExpendh(Starttime,Endtime);
                                int timelong3= Integer.parseInt(timelong2);
                                mTvTimeL.setText("时长："+timelong);
                                CountNumbers c2= (CountNumbers) getApplication();
                                c2.setTempreture(String.valueOf(a2));
                                c2.setTimelong(timelong);

                                if(timelong1!=0){
                                    if(timelong3==timelong1){
                                        byte[] start= new byte[]{0x36, (byte) 0xf1, 0x04, 0x00, 0x00, 0x00, (byte) 0xc3,(byte) 0xff};
                                        Ch340write(start);
                                        handler2.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                Message msg=new Message();
                                                msg.what=3;
                                                handler2.sendMessage(msg);
                                            }
                                        },1000);
                                        Message message=new Message();
                                        message.what=3;
                                        handler2.sendMessage(message);
                                        stopBn.setImageResource(R.mipmap.start);
                                        isFirst=true;
                                        CountNumbers c1=new CountNumbers();
                                        c1.setStatus(true);
                                        try {
                                            mSharedPreferences =getSharedPreferences("data",MODE_PRIVATE);//数据端口打开
                                            mEditor = mSharedPreferences.edit();
                                            ArrayList<String> mfristData = new ArrayList<String>();
                                            mfristData = readFile(getFilesDir().getParent()+"/files/test.txt");
                                            ArrayList<Integer> iddelete =DataBaseTool.getid(MainActivity.this,1,TABLE_NAME2);
                                            ArrayList<ArrayList<String>> show =DataBaseTool.getlist6(MainActivity.this,1,TABLE_NAME2);
                                            //设置单元格内容
                                            ArrayList<String> a1=show.get(show.size()-1);
                                            String a=a1.get(0);
                                            String b=a1.get(1);
                                            String c=a1.get(2);
                                            String d=a1.get(3);
                                            String e=a1.get(4);
                                            DataBaseTool.changdata(MainActivity.this,1,TABLE_NAME2,iddelete.get(show.size()-1),a,b,c,d,e, String.valueOf(mfristData),null);
                                            ToastUtil.showMsg(MainActivity.this,c);
                                        }catch (Exception e){
                                            Log.e("数据库:","不存在");
                                        }
                                        File file = new File(getFilesDir().getParent()+"/files/test.txt");
                                        if(file.exists()){
                                            deleteFile("test.txt");
                                            Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                                        }

                                        iscountinue=false;
                                    }
                                }
                            }

                            break;
                        case (byte) 0x90:
                            timer3.cancel();
                            waitdialog.dismiss();
                            hideBottomUIMenu();
                            Message mesg=new Message();
                            mesg.what=1;
                            handler2.sendMessage(mesg);
                            Starttime=getsystemtime();
                            byte[] d1= new byte[]{0x36, (byte) 0xf1, 0x09, 0x00, 0x00, 0x00, (byte) 0xce, (byte) 0xff};
                            Ch340write(d1);
                            isstart1=true;
                            ToastUtil.showMsg(MainActivity.this,"可以放入试管了");
                            isTest=true;
                            break;
                        case (byte) 0x80:
                            is80=true;
                            bt=0;
                            break;
                        case (byte) 0xa0:
                            byte[] f= new byte[]{0x36, (byte) 0xf1, 0x0B, 0x00, 0x00, 0x00, (byte) 0xcc, (byte) 0xff};
                            Ch340write(f);
                            MyApp.driver.CloseDevice();
                            ActivityCollector.finishAllActivity();
                            break;
                        case (byte) 0x60:
                            File file = new File(getFilesDir().getParent()+"/files/test.txt");
                            if(file.exists()){
                                deleteFile("test.txt");
                                Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                            }
//                            dodata();
//                            alllineset();
                            isFirst=true;
                            iscountinue=false;
                            CountNumbers c2=new CountNumbers();
                            c2.setStatus(true);
                            stopBn.setImageResource(R.mipmap.start);
                            CountNumbers c1=new CountNumbers();
                            c1.setStatus(true);
                            break;
                        case (byte) 0x40:
                            byte[] b= new byte[]{0x36, (byte) 0xf1, 0x05, 0x00, 0x00, 0x00, (byte) 0xc2, (byte) 0xff};
                            Ch340write(b);
                            is40=true;
                            break;
                        default:
                            break;
                    }

                };
            }else {
                if(check[1]!=(byte) 0xf1) {
                    byte[] d1 = new byte[]{0x36, (byte) 0xf1, 0x06, 0x00, 0x00, 0x00, (byte) 0xc1, (byte) 0xff};
                    Ch340write(d1);
                    Log.i("数据错误：","");
                }
                check123=false;
            };
        }

    };


    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hideBottomUIMenu();

        initUI();

        initSingelShowFragment();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideBottomUIMenu();
                        }
                    });
                }
            }
        }).start();
    }


    //返回键监听
    @Override
    public void onBackPressed() {
        hideBottomUIMenu();
    }

    //初始化控件
    private void initUI() {
        testBn = findViewById(R.id.testBn);
        resultBn = findViewById(R.id.resultBn);
        settingBn = findViewById(R.id.settingBn);
        testBn.setOnClickListener(this);
        resultBn.setOnClickListener(this);
        settingBn.setOnClickListener(this);

        signBn = findViewById(R.id.signupBn);
        right1Bn = findViewById(R.id.right1Bn);
        right2Bn = findViewById(R.id.right2Bn);
        signBn.setOnClickListener(this);
        right1Bn.setOnClickListener(this);
        right2Bn.setOnClickListener(this);

        mIvOpen = findViewById(R.id.Iv_open);
        mIvPrint = findViewById(R.id.Iv_print);
        mIvNetwork = findViewById(R.id.Iv_network);
        mIvOpen.setOnClickListener(this);

    }

    //隐藏所有Fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (singelShowFragment != null) {
            transaction.hide(singelShowFragment);
        }
        if (resultFragment != null) {
            transaction.hide(resultFragment);
        }
        if (settingFragment != null) {
            transaction.hide(settingFragment);
        }
        if (mutilShowFragment != null) {
            transaction.hide(mutilShowFragment);
        }
        if (grameSettingFragment != null) {
            transaction.hide(grameSettingFragment);
        }
        if (peopleSettingFragment != null) {
            transaction.hide(peopleSettingFragment);
        }
        if (systemSettingFragment != null) {
            transaction.hide(systemSettingFragment);
        }
        if (startSetFragment != null) {
            transaction.hide(startSetFragment);
        }
    }

    //显示曲线单图
    private void initSingelShowFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (singelShowFragment == null) {
            singelShowFragment = new SingelShowFragment();
            transaction.add(R.id.main_show, singelShowFragment);
        }
        hideFragment(transaction);
        transaction.show(singelShowFragment);
        transaction.commit();
    }

    //显示16宫图界面
    private void initMultiShowFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mutilShowFragment == null) {
            mutilShowFragment = new MutilShowFragment();
            transaction.add(R.id.main_show, mutilShowFragment);
        }
        hideFragment(transaction);
        transaction.show(mutilShowFragment);
        transaction.commit();
    }

    //显示结果界面
    private void initResultFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (resultFragment == null) {
            resultFragment = new ResultFragment();
            transaction.add(R.id.main_show, resultFragment);
        }

        hideFragment(transaction);
        transaction.show(resultFragment);

        transaction.commit();
    }

    //显示设置界面
    public void initSettingFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (settingFragment == null) {
            settingFragment = new SettingFragment();
            transaction.add(R.id.main_show, settingFragment);
        }
        hideFragment(transaction);
        transaction.show(settingFragment);

        transaction.commit();
    }

    //显示菌种设置界面
    public void initGrameSettingFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (grameSettingFragment == null) {
            grameSettingFragment = new GrameSettingFragment();
            transaction.add(R.id.main_show, grameSettingFragment);
        }
        hideFragment(transaction);
        transaction.show(grameSettingFragment);
        transaction.commit();
    }

    //人员设置界面
    public void initPeopleSettingFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (peopleSettingFragment == null) {
            peopleSettingFragment = new PeopleSettingFragment();
            transaction.add(R.id.main_show, peopleSettingFragment);
        }
        hideFragment(transaction);
        transaction.show(peopleSettingFragment);
        transaction.commit();
    }

    //系统设置界面
    public void initSystemFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (systemSettingFragment == null) {
            systemSettingFragment = new SystemSettingFragment();
            transaction.add(R.id.main_show, systemSettingFragment);
        }
        hideFragment(transaction);
        transaction.show(systemSettingFragment);
        transaction.commit();
    }

    //显示菌种设置界面
    private void initStartSetFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (startSetFragment == null) {
            startSetFragment = new StartSetFragment();
            transaction.add(R.id.main_show, startSetFragment);
        }
        hideFragment(transaction);
        transaction.show(startSetFragment);
        transaction.commit();
    }


    //隐藏状态栏和导航键
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    //监听点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.testBn:
                initSingelShowFragment();
                testBn.setImageResource(R.mipmap.test_selected);
                resultBn.setImageResource(R.mipmap.result_unselect);
                settingBn.setImageResource(R.mipmap.setting_unselect);
                right1Bn.setImageResource(R.mipmap.start);
                right2Bn.setImageResource(R.mipmap.change);
                break;
            case R.id.resultBn:
                initResultFragment();
                testBn.setImageResource(R.mipmap.test_unselect);
                resultBn.setImageResource(R.mipmap.result_selected);
                settingBn.setImageResource(R.mipmap.setting_unselect);
                right1Bn.setImageResource(R.mipmap.printui);
                right2Bn.setImageResource(R.mipmap.outputui);
                break;
            case R.id.settingBn:
                initSettingFragment();
                testBn.setImageResource(R.mipmap.test_unselect);
                resultBn.setImageResource(R.mipmap.result_unselect);
                settingBn.setImageResource(R.mipmap.setting_selected);
                right1Bn.setImageResource(R.mipmap.setting_printer);
                right2Bn.setImageResource(R.mipmap.setting_about);
                break;
            case R.id.signupBn:

                break;
            case R.id.right1Bn:
                if (testBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.test_selected).getConstantState())){
                    //处于检测界面时此按钮未开始或暂停
                    if (right1Bn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.start).getConstantState())) {
                        initStartSetFragment();
                    }
                }
                if (resultBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.result_selected).getConstantState())) {
                    //处于结果界面此按钮功能为打印
                }
                if (settingBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.setting_selected).getConstantState())){
                    //处于检测界面时此按钮功能为打印机设置
                }
                break;
            case R.id.right2Bn:
                if (testBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.test_selected).getConstantState())){
                    //处于检测界面时此按钮功能为切换
                    if (right2Bn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.change).getConstantState())) {
                        initMultiShowFragment();
                        right2Bn.setImageResource(R.mipmap.change2);
                    } else {
                        initSingelShowFragment();
                        right2Bn.setImageResource(R.mipmap.change);
                    }
                }
                if (resultBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.result_selected).getConstantState())) {
                    //处于结果界面此按钮功能为导出
                }
                if (settingBn.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.setting_selected).getConstantState())){
                    //处于检测界面时此按钮功能为关于
                }
                break;
            case R.id.Iv_open:
                //一个弹窗，防止顾客误点
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("请选择").setMessage("您是否要关闭此程序")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCollector.finishAllActivity();
                            }
                        })
                        .setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "您取消了关闭此程序", Toast.LENGTH_SHORT).show();
                            }
                        }).show();
                break;
            default:
                break;
        }
    }
    private void mCH340(){
        MyApp.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        if (!MyApp.driver.UsbFeatureSupported())// USB HOST
        {
            Dialog dialog = new android.app.AlertDialog.Builder(MainActivity.this)
                    .setTitle("权限")
                    .setMessage("===============USB HOST==============")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            isOpen = false;
        }
    }
    //打开串口
    private void mOpenCH340(){
        if (!isOpen) {
            int retval = MyApp.driver.ResumeUsbPermission();
            if (retval == 0) {
                //Resume usb device list
                retval = MyApp.driver.ResumeUsbList();
                if (retval == -1)// ResumeUsbList     CH34X
                {
                    Toast.makeText(MainActivity.this, "Open failed!",
                            Toast.LENGTH_SHORT).show();
                    Log.e("ch34","打开失败");
                    MyApp.driver.CloseDevice();
                } else if (retval == 0){
                    if (MyApp.driver.mDeviceConnection != null) {
                        if (!MyApp.driver.UartInit()) {
                            Toast.makeText(MainActivity.this, "Initialization failed!",
                                    Toast.LENGTH_SHORT).show();
                            Log.e("ch34","打开cg");
                            return;
                        }
                        Toast.makeText(MainActivity.this, "Device opened",
                                Toast.LENGTH_SHORT).show();
                        isOpen = true;
                        new readThread().start();
                    } else {
                        Toast.makeText(MainActivity.this, "Open failed!",
                                Toast.LENGTH_SHORT).show();
                        Log.e("ch34","打开失败");
                    }
                } else {
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
                    builder.setIcon(R.drawable.editshape);
                    builder.setTitle("好好吃饭");
                    builder.setMessage("好好学习˳天天向上");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub

                        }
                    });
                    builder.show();

                }
            }
        } else {

            isOpen = false;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            MyApp.driver.CloseDevice();
        }
    }

    private void Ch340config(){
        baudRate = 115200;
        dataBit = 8;
        stopBit = 1;
        parity = 0;
        flowControl = 0;
        if (MyApp.driver.SetConfig(baudRate, dataBit, stopBit, parity,
                flowControl)) {
            Toast.makeText(MainActivity.this, "Config successfully",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Config failed!",
                    Toast.LENGTH_SHORT).show();
        }
    }
    private void Ch340write(byte[] commit){
        byte[] to_send = commit;
        int retval=0;
        if(to_send.length == 8){
            retval = MyApp.driver.WriteData(to_send, to_send.length);
        }
//				byte[] to_send = toByteArray2(writeText.getText().toString());

        if (retval < 0)
            Toast.makeText(MainActivity.this, "Write failed!",
                    Toast.LENGTH_SHORT).show();

    }

    protected void onDestroy() {
        super.onDestroy();
        byte[] b= new byte[]{0x36, (byte) 0xf1, 0x05, 0x00, 0x00, 0x00, (byte) 0xc2, (byte) 0xff};
        Ch340write(b);
        ActivityCollector.removeActivity(this);//当一个Activity调用onDestroy方法时，就将其从activity列表中删除

    }
    private class readThread extends Thread {

        public void run() {

            byte[] buffer = new byte[1024];

            while (true) {

                Message msg = Message.obtain();
                Message msg1 = Message.obtain();
                Message msg2 = Message.obtain();
                Message msg3 = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = MyApp.driver.ReadData(buffer, 1024);
//                if (length > 0) {
//                    String recv = toHexString(buffer, length);
//                    msg.obj = recv;
//                    handler.sendMessage(msg);
//                    Log.i("length", String.valueOf(length));
//                }
                switch (length){
                    case 8:
                        String recv = toHexString(buffer, length);
                        msg.obj = recv;
                        handler.sendMessage(msg);
                        break;
                    case 16:
                        byte[] buffer1=new byte[]{buffer[0],buffer[1],buffer[2],buffer[3],buffer[4],buffer[5],buffer[6],buffer[7]};
                        byte[] buffer2=new byte[]{buffer[8],buffer[9],buffer[10],buffer[11],buffer[12],buffer[13],buffer[14],buffer[15]};
                        String recv1 = toHexString(buffer1, 8);
                        String recv2 = toHexString(buffer2, 8);
                        msg.obj = recv1;
                        handler.sendMessage(msg);
                        msg1.obj = recv2;
                        handler.sendMessage(msg1);
                        break;
                    case 24:
                        byte[] buffer11=new byte[]{buffer[0],buffer[1],buffer[2],buffer[3],buffer[4],buffer[5],buffer[6],buffer[7]};
                        byte[] buffer12=new byte[]{buffer[8],buffer[9],buffer[10],buffer[11],buffer[12],buffer[13],buffer[14],buffer[15]};
                        byte[] buffer13=new byte[]{buffer[16],buffer[17],buffer[18],buffer[19],buffer[20],buffer[21],buffer[22],buffer[23]};
                        String recv11 = toHexString(buffer11, 8);
                        String recv12 = toHexString(buffer12, 8);
                        String recv13 = toHexString(buffer13, 8);
                        msg.obj = recv11;
                        handler.sendMessage(msg);
                        msg1.obj = recv12;
                        handler.sendMessage(msg1);
                        msg2.obj=recv13;
                        handler.sendMessage(msg2);
                        break;
                    case 32:
                        byte[] buffer21=new byte[]{buffer[0],buffer[1],buffer[2],buffer[3],buffer[4],buffer[5],buffer[6],buffer[7]};
                        byte[] buffer22=new byte[]{buffer[8],buffer[9],buffer[10],buffer[11],buffer[12],buffer[13],buffer[14],buffer[15]};
                        byte[] buffer23=new byte[]{buffer[16],buffer[17],buffer[18],buffer[19],buffer[20],buffer[21],buffer[22],buffer[23]};
                        byte[] buffer24=new byte[]{buffer[24],buffer[25],buffer[26],buffer[27],buffer[28],buffer[29],buffer[30],buffer[31]};
                        String recv21 = toHexString(buffer21, 8);
                        String recv22 = toHexString(buffer22, 8);
                        String recv23 = toHexString(buffer23, 8);
                        String recv24 = toHexString(buffer24, 8);
                        msg.obj = recv21;
                        handler.sendMessage(msg);
                        msg1.obj = recv22;
                        handler.sendMessage(msg1);
                        msg2.obj=recv23;
                        handler.sendMessage(msg2);
                        msg3.obj=recv24;
                        handler.sendMessage(msg3);
                        break;
                    default:
                        break;
                }
            }
        }
    }
    private byte[] toByteArray(String arg) {
        if (arg != null) {

            char[] NewArray = new char[1000];
            char[] array = arg.toCharArray();
            int length = 0;
            for (int i = 0; i < array.length; i++) {
                if (array[i] != ' ') {
                    NewArray[length] = array[i];
                    length++;
                }
            }

            int EvenLength = (length % 2 == 0) ? length : length + 1;
            if (EvenLength != 0) {
                int[] data = new int[EvenLength];
                data[EvenLength - 1] = 0;
                for (int i = 0; i < length; i++) {
                    if (NewArray[i] >= '0' && NewArray[i] <= '9') {
                        data[i] = NewArray[i] - '0';
                    } else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {
                        data[i] = NewArray[i] - 'a' + 10;
                    } else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {
                        data[i] = NewArray[i] - 'A' + 10;
                    }
                }

                byte[] byteArray = new byte[EvenLength / 2];
                for (int i = 0; i < EvenLength / 2; i++) {
                    byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]);
                }
                return byteArray;
            }
        }
        return new byte[] {};
    }
    private String toHexString(byte[] arg, int length) {
        String result = new String();
        if (arg != null) {
            for (int i = 0; i < length; i++) {
                result = result
                        + (Integer.toHexString(
                        arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
                        + Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])
                        : Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])) + " ";
            }
            return result;
        }
        return "";
    }
    //异或校验
    private byte jocheck(byte[] check){
        byte checked = 0x36;
        for (int i=1;i<check.length-2;i++){
            checked= (byte) (checked^check[i]);
        }
        return checked;
    }
    public static final int btou(byte b) {
        if (b >= 0)
            return (b + 0);
        else
            return (256 + b);
    }
    private void save(String content){
        try {
            FileOutputStream fileOutputStream=openFileOutput(mFileName,MODE_APPEND);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**逐行读取文件
     * @param strFilePath
     */
    public ArrayList<String> readFile(String strFilePath){
        ArrayList<String> txtList = new ArrayList<>();
        File file = new File(strFilePath);
        if (file.isDirectory()){
            Log.e( "文件不存在","The File doesn't not exist.");
        }else{
            try{
                InputStream instream = new FileInputStream(file);
                if (instream != null){
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //逐行读取
                    while (( line = buffreader.readLine()) != null){
                        txtList.add(line);
                    }

                    instream.close();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return txtList;
    }
    private String getTimeExpend(long startTime, long endTime){
        //传入字串类型 2016/06/28 08:30
        long longExpend =endTime - startTime;  //获取时间差

        long longHours = longExpend / (60 * 60 * 1000); //根据时间差来计算小时数
        long longMinutes = (longExpend - longHours * (60 * 60 * 1000)) / (60 * 1000);   //根据时间差来计算分钟数
        return longHours + ":" + longMinutes;
    }
    private String getTimeExpendh(long startTime, long endTime){
        //传入字串类型 2016/06/28 08:30
        long longExpend = endTime -startTime;  //获取时间差

        long longHours = longExpend / (60 * 60 * 1000); //根据时间差来计算小时数
        long longMinutes = (longExpend - longHours * (60 * 60 * 1000)) / (60 * 1000);   //根据时间差来计算分钟数

        return String.valueOf(longHours);
    }
    private Timer timer3;
    private void setTimedialog(int te){
        waitdialog=new ShowDownloadDialog(MainActivity.this);
        waitdialog.setTitle("请等待温度加热");
        waitdialog.setSettemp(te*100);
        hideBottomUIMenu();
        waitdialog.show();
        timer3=new Timer();
        timer3.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg=new Message();
                msg.what=5;
                handler2.sendMessage(msg);
            }
        },0,3000);
    }
    //得到日期时间
    private String getsystemtime1(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
    private long getsystemtime(){
        long time=System.currentTimeMillis();
        return time;
    }
    private byte translate(byte[] check){
        byte checked = 0x36;
        for (int i=1;i<check.length-1;i++){
            checked= (byte) (checked^check[i]);
        }
        return checked;

    }
}
